package com.jf3q.gateway.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.jf3q.common.constant.ResultCode;
import com.jf3q.common.dto.ResultDto;
import com.jf3q.gateway.security.entity.AclUser;
import com.jf3q.gateway.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {


    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders httpHeaders = response.getHeaders();
        httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
        httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        //设置body


        byte[] dataBytes = {};
        ObjectMapper mapper = new ObjectMapper();
        try {

            User user=(User)authentication.getPrincipal();
            AclUser userDetails=buildUser(user);
            byte[] authorization = (userDetails.getUsername() + ":" + userDetails.getPassword()).getBytes();

            //生成token  jwt
            String token = jwtTokenUtil.getToken(userDetails.getUsername());
            ResultDto resultDto = ResultDto.success("认证成功",token);
            dataBytes = mapper.writeValueAsBytes(resultDto);
        } catch (Exception ex) {
            ex.printStackTrace();

            //alibaba fastjson  jackson   gson
            JsonObject result = new JsonObject();
            result.addProperty("status", ResultCode.ERROR.getCode());
            result.addProperty("message", "认证异常");
            dataBytes = result.toString().getBytes();
        }
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }

    private AclUser  buildUser(User user){
        AclUser userDetails=new AclUser();
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPassword().substring(user.getPassword().lastIndexOf("}")+1,user.getPassword().length()));
        return userDetails;
    }


}
